package lc.q1_50;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * 给定一个 没有重复 数字的序列，返回其所有可能的全排列。
 */
public class Q46 {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        if (nums.length == 0) {
            return results;
        }
        boolean[] used = new boolean[nums.length];
        dfs(nums, nums.length, 0, used, new ArrayDeque<>(nums.length), results);
        return results;
    }

    public void dfs(int[] nums, int length, int depth,boolean[] used,
                    Deque<Integer> deque, List<List<Integer>> results) {
        // 回溯
        if (length == depth) {
            results.add(new ArrayList<>(deque));
            return;
        }
        for (int i = 0; i < length; i++) {
            if (used[i]) {
                continue;
            }
            deque.addLast(nums[i]);
            used[i] = true;
            dfs(nums, length, depth + 1, used, deque, results);
            used[i] = false;
            deque.removeLast();
        }
    }

    public static void main(String[] args) {
        final Q46 q46 = new Q46();
        int[] nums = new int[]{1,2,3};
        System.out.println(q46.permute(nums));
    }
}
